// pages/order/order.js
const app = getApp()
import Api from '../../utils/api';
import util from '../../utils/util';
var searchBillInterval;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    array: ['快递', '到店自提', '壹配送','到店消费'],
    deliveryType: ['POST', "ZT", 'YPS','CONSUME'], //YPS壹配送到家  ZT自提 POST邮寄
    indexType: 0,  //获取可选配送方式的索引
    spellType: '', //LIMITED_TIME: 限时 GROUP: 拼团
    templateId: '', //拼团模板id
    goodsInfo: {}, //商品信息
    isAddGroup: false,//是否是加入拼团 必传项
    num: 1, //数量
    couponId: "", //红包id
    addressId: '', //地址id
    isGetAddress: false, //是否有地址信息
    spellInfo: {}, //预览信息
    taskId: "", //拼团任务id
    storeCount: 0,//库存
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let _this = this;
    console.log(options)
    if (options.spellType != undefined){
      if (options.spellType == "GROUP"){ //拼团
        if (options.isAddGroup != 1){ //加入拼团获取拼团任务id
          _this.setData({
            taskId: options.taskId
          })
        }
        _this.setData({
          isAddGroup: options.isAddGroup == 1 ? false : true,
          spellType: options.spellType,
          templateId: options.templateId
        })
        console.log(_this.data.isAddGroup)
        _this.spellDetail();
      }else{
        _this.setData({
          isAddGroup: options.isAddGroup == 1  ? false : true,
          spellType: options.spellType,
          templateId: options.templateId
        })
        console.log(_this.data.isAddGroup)
        _this.spellDetail();
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let _this = this;
    _this.getAddress();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    app.globalData.otherPageHideFlag = true;
  },
  // 配送方式选择
  bindPickerChange: function (e) {
    //console.log(e)
    let _this = this;
    var type = _this.data.array[e.detail.value];
    _this.setData({
      indexType: e.detail.value,
    })
    //console.log(_this.data.indexType)
    _this.spellOrderInfo();
  },

  //获取详情页信息
  spellDetail() {
    let _this = this;
    Api.spellDetail(_this.data.templateId).then(res => {
      console.log("获取拼团模板信息", res)
      _this.setData({
        goodsInfo: res.data,
        storeCount: res.data.newest.storeCount,
      })
      if (_this.data.spellType == "GROUP"){ //拼团获取的是库存
        _this.setData({
          storeCount: res.data.newest.storeCount,
        })
      }else{ //秒杀获取的 秒杀数量
        _this.setData({
          storeCount: res.data.limitedSpellNum,
        })
      }
    })
  },

  //获取默认地址
  getAddress(callback) {
    let _this = this;
    if (_this.data.addressId == '') {
      Api.getDefaultAddress().then(res => {
        console.log(res)
        if(res.data){
          _this.setData({
            userAddress: res.data,
            isGetAddress: true,
            addressId: res.data.id
          });
        }
        _this.isEqualCity();
        //(callback && typeof (callback) === "function") && callback();
      })
    } else {
      Api.queryAddressId(_this.data.addressId).then(res => {
        //console.log(res)
        _this.setData({
          userAddress: res.data,
          isGetAddress: true,
          // addressId: res.data.id
        });
        _this.isEqualCity();
        // (callback && typeof (callback) === "function") && callback();
      })
    }
  },

  //判断当前城市和收货地址城市是否一致
  isEqualCity() {
    let _this = this;
    let userCity = new RegExp(_this.data.goodsInfo.cityName);
    if (_this.data.userAddress && userCity.test(_this.data.userAddress.city)) {
      _this.setData({
        array: ['快递', '到店自提', '壹配送','到店消费'],
        deliveryType: ['POST', "ZT", 'YPS','CONSUME'],
        indexType: 0,
      })
    } else {
      _this.setData({
        array: ['快递', '到店自提','到店消费'],
        deliveryType: ['POST',"ZT",'CONSUME'],
        indexType: 0,
      })
    }
    _this.spellOrderInfo()
  },

  //减法
  reduceClick(e) {
    let _this = this;
    if (_this.data.num <= 1) {
      _this.setData({
        num: 1
      })
      return;
    }
    _this.setData({
      num: _this.data.num - 1,
    })
    _this.spellOrderInfo();
  },

  //加法
  addClick(e) {
    let _this = this;
    if(_this.data.num < _this.data.storeCount){
      _this.setData({
        num: _this.data.num + 1,
      })
      _this.spellOrderInfo();
    }else{
      if (_this.data.spellType == "GROUP"){ //拼团
        wx.showToast({
          title: '超出现有库存',
          icon: 'loading',
          duration: 2000
        })
      }else{ //秒杀
        wx.showToast({
          title: '超出秒杀数量',
          icon: 'loading',
          duration: 2000
        })
      }
     
    }
    
    //console.log("加法", _this.data.cartItemDtoList[index].num)
  },
  //预览订单信息
  spellOrderInfo(){
    let _this = this;
    let data = {
      "isAddGroup": _this.data.isAddGroup,
      "taskId": _this.data.taskId,
      "addressId": _this.data.addressId,
      "deliveryType": _this.data.deliveryType[_this.data.indexType],
      "templateId": _this.data.templateId,
      "num": _this.data.num,
    }
    console.log(data)
    Api.spellOrderInfo(data).then( res => {
      console.log("预览订单信息",res)
      _this.setData({
        spellInfo: res.data
      })
    })
  },

  //创建订单
  submitInfo(e){
    let _this = this;
    console.log(e.detail.formId);
    _this.setData({
      formId: e.detail.formId
    });
    if (!_this.data.addressId && (_this.data.deliveryType[_this.data.indexType] == 'POST' || _this.data.deliveryType[_this.data.indexType] == 'YPS')) {
      wx.showToast({
        title: '请选择收件地址',
        icon: 'none'
      })
      return
    }
    _this.createSpellOrder();
  },

  //创建订单
  createSpellOrder() {
    let _this = this;
    let data = {
      "isAddGroup": _this.data.isAddGroup,
      "taskId": _this.data.taskId,
      "addressId": _this.data.addressId, //地址id
      "deliveryType": _this.data.deliveryType[_this.data.indexType],  //配送方式  [ '快递','到店自提', '壹配送'],['POST',"ZT", 'YPS'],
      "payType": "WX_JSAPI",  //支付方式  
      "templateId": _this.data.templateId,//模板id
      "num": _this.data.num, //数量
      "remarks": _this.data.remarks, //备注 
      "formId": _this.data.formId,  //表单ID
    }
    console.log(data)
    Api.createSpellOrder(data).then(res => {
      console.log("创建订单", res)
      let payString = JSON.parse(res.data.bill.payString);
      let billId = res.data.bill.billId;
      //console.log(typeof payString)
      wx.requestPayment({
        timeStamp: payString.timeStamp,
        nonceStr: payString.nonceStr,
        package: payString.package,
        signType: payString.signType,
        paySign: payString.paySign,
        success(res) {
          //console.log(res)
          wx.showLoading({
            title: '订单创建中',
          })
          //轮询查询支付状态
          searchBillInterval = setInterval(() => {
            console.log('支付账单号',billId);
            Api.queryBillPayStatus(billId).then(response => {
              console.log('账单查询轮询中...', response)
              if (response.data) {
                wx.hideLoading()
                if (searchBillInterval){
                  console.log('账单支付轮询已关闭');
                  clearInterval(searchBillInterval);
                }
                wx.hideLoading()
                if (_this.data.spellType == "GROUP") {
                  wx.redirectTo({
                    url: '/pages/seeOrder/seeOrder?orderStatusIndex=0',
                  })
                } else {
                  wx.redirectTo({
                    url: '/pages/seeOrder/seeOrder?orderStatusIndex=3',
                  })
                }
              }
            });
          }, "1000")
        },
        fail(res) {
          //console.log(res)
          wx.showLoading({
            title: '订单取消中',
          })
          setTimeout(function () {
            wx.hideLoading()
            wx.redirectTo({
              url: '/pages/seeOrder/seeOrder?orderStatusIndex=1',
            })
          }, 2000)
          
        },
        complete(res) {
          console.log('spellOrder.js==========调用了微信支付页面complete')
          app.globalData.otherPageHideFlag = true;
        }
      })
    })
  },

})